package com.slipper.common.controller;

import com.slipper.common.bo.UserDetail;
import com.slipper.constants.Constants;
import com.slipper.core.file.FileServiceUtil;
import com.slipper.core.file.vo.FileVO;
import com.slipper.system.affix.bo.AffixItemBO;
import com.slipper.system.affix.common.AffixInfo;
import com.slipper.system.affix.service.AffixItemService;
import com.slipper.util.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private AffixItemService affixItemService;

    @PostMapping(value = "/queryItem")
    public String queryItem(@RequestBody AffixItemBO bo) {
        return ResultUtil.successResult(this.affixItemService.queryBy(bo.getId()));
    }

    @PostMapping(value = "/queryItems")
    public String queryItems(@RequestBody AffixItemBO bo) {
        return ResultUtil.successResult(this.affixItemService.queryList(bo));
    }

    @PostMapping(value = "/deleteItem")
    public String deleteItem(@RequestBody AffixItemBO bo) {
        // 获取用户，未登录时抛出异常，必须登录才可以做删除操作
        Constants.getCurrentUser();

        if (Tool.isBlank(bo.getId())) {
            return ResultUtil.failureResult("参数不正确!");
        }

        return ResultUtil.deleteResult(this.affixItemService.delete(bo.getId()));
    }

    /**
     * 附件上传
     */
    @PostMapping(value = "/upload")
    public String upload(AffixInfo info) throws Exception {
        FileVO fileVO;
        if (info.getBase64() != null) {
            fileVO = FileServiceUtil.saveFile(info.getFileName(), info.getBase64());
        } else if (info.getFile() != null) {
            String fileName = info.getFileName() == null ? info.getFile().getOriginalFilename() : info.getFileName();
            fileVO = FileServiceUtil.saveFile(fileName, info.getFile().getInputStream());
        } else {
            return ResultUtil.failureResult("请上传附件！");
        }

        if (Tool.isNotBlank(info.getFileId())) {
            AffixItemBO affixItem = this.affixItemService.queryBy(info.getFileId());
            if (affixItem != null) {
                affixItem.setSaveMode(fileVO.getMode());
                affixItem.setTrueName(fileVO.getName());
                affixItem.setSavePath(fileVO.getPath());
                affixItem.setFileSize(fileVO.getSize());
                this.affixItemService.save(affixItem);
                return ResultUtil.successResult(affixItem);
            }
        }

        UserDetail userDetail = Constants.getCurrentUser();
        AffixItemBO affixItem = new AffixItemBO();
        affixItem.setAffixId(info.getAffixId());
        affixItem.setSaveMode(fileVO.getMode());
        affixItem.setType(info.getType());
        affixItem.setTrueName(fileVO.getName());
        affixItem.setSavePath(fileVO.getPath());
        affixItem.setFileSize(fileVO.getSize());
        affixItem.setBuiltin(info.getBuiltin());
        affixItem.setCreateId(userDetail.getEmployeeId());
        affixItem.setCreateTime(System.currentTimeMillis());
        return ResultUtil.successResult(this.affixItemService.save(affixItem));
    }

    /**
     * 文件下载
     */
    @PostMapping("/download")
    public void download(HttpServletResponse response, @RequestBody AffixItemBO bo) throws Exception {
        if (Tool.isBlank(bo.getId())) return;
        AffixItemBO affixItemBO = this.affixItemService.queryBy(bo.getId());
        if (affixItemBO == null) {
            this.logger.error("文件不存在: {}", bo.getId());
            return;

        }

        FileUtil.download(response, affixItemBO.getTrueName(), FileServiceUtil.readFile(affixItemBO.getSavePath()));
    }

    /**
     * 打包下载
     */
    @PostMapping("/downloadAll")
    public void downloadAll(HttpServletResponse response, @RequestBody AffixItemBO bo) throws Exception {
        List<AffixItemBO> list = this.affixItemService.queryList(bo);
        if (!list.isEmpty()) {
            if (list.size() == 1) {
                AffixItemBO affixItem = list.getFirst();
                FileUtil.download(
                        response,
                        affixItem.getTrueName(),
                        FileServiceUtil.readFile(affixItem.getSavePath()));
            } else {
                List<String> filePathList = new ArrayList<>();
                List<String> fileNameList = new ArrayList<>();
                for (AffixItemBO affixItem : list) {
                    fileNameList.add(affixItem.getTrueName());
                    filePathList.add(affixItem.getSavePath());
                }

                String fileName = "附件打包" + DateUtil.format(new Date(), "yyyyMMdd")+ ".zip";
                FileUtil.downloadZip(response, fileName, fileNameList, filePathList);
            }
        }
    }

    /**
     * 获取附件列表
     */
    @PostMapping(value = "/queryList")
    public String queryList(@RequestBody AffixItemBO bo) {
        return ResultUtil.successResult(this.affixItemService.queryList(bo));
    }

    @GetMapping({"/image/{id}", "/file/{id}"})
    public void file(HttpServletResponse response, @PathVariable("id") String id) throws Exception {
        if (Tool.isBlank(id)) return;

        AffixItemBO affixItem = this.affixItemService.queryBy(id);
        if (affixItem == null) {
            affixItem = this.affixItemService.queryByAffixId(id);
        }
        if (affixItem == null) {
            this.logger.error("参数不正确，文件不存在: {}", id);
            return;
        }

        FileUtil.download(response, affixItem.getTrueName(), FileServiceUtil.readFile(affixItem.getSavePath()));
    }
}
